import store from '../store/index.js'
let isRefreshing = true
let subscribers = []
let baseUrl //基础地址
// ! 测试环境地址
if (process.env.NODE_ENV === 'development') {
	// baseUrl = 'http://dream.sh1.k9s.run:2271'
	// baseUrl = '192.168.17'
	// baseUrl = 'http://yzq.sh1.k9s.run:2271'
	baseUrl = 'https://crxsukrt1h5k.ngrok2.xiaomiqiu.cn'
	// baseUrl = 'http://local110.sh1.k9s.run:2271'
}
// ! 生产环境地址
if (process.env.NODE_ENV === 'production') {
	baseUrl = 'https://crxsukrt1h5k.ngrok2.xiaomiqiu.cn'
}
function onAccessTokenFetched() {
	subscribers.forEach(callback => {
		callback()
	})
	subscribers = []
}

function addSubscriber(callback) {
	subscribers.push(callback)
}

// export class Http {
//   constructor() { }

export const request = ({
	url,
	data = {},
	method,
	header,
	callback = '',
} = {}) => {
	const reqUrl = baseUrl + url
	return new Promise((resolve, reject) => {
		uni.request({
			url: reqUrl,
			data,
			method,
			header: { Authorization: uni.getStorageSync('token') || null },
			callback,
			fail(res) {
				reject(res)
			},
			complete: res => {
				if (callback) return callback(res.data)
				let statusCode = res.statusCode || ''
				if (statusCode == 404) {
					console.log('接口不存在')
				} else if (statusCode == 401) {
					// 将需要重新执行的接口缓存到一个队列中
					addSubscriber(() => {
						request({ url, data, method, header, callback: resolve })
					})
					if (isRefreshing) {
						getNewToken().then(() => {
							// 依次去执行缓存的接口
							onAccessTokenFetched()
							isRefreshing = true
						})
					}
					isRefreshing = false
				} else if (statusCode == 200) {
					const code = res.data.head.code
					if (code == 401) {
						addSubscriber(() => {
							request({ url, data, method, header, callback: resolve })
						})

						if (isRefreshing) {
							getNewToken()
								.then(() => {
									// 依次去执行缓存的接口
									onAccessTokenFetched()
									isRefreshing = true
								})
								.catch(() => { })
						}
						isRefreshing = false
					} else if (String(code).startsWith('5')) {
						uni.showModal({
							content: '服务器报错，请重试！',
							showCancel: false,
						})
						reject(res)
					} else {
						resolve(res.data)
					}
				} else if (statusCode.startsWith('5')) {
					uni.showModal({ content: '服务器报错，请重试！', showCancel: false })
					reject(res)
				}
			},
		})
	})
}
// }
// 获取token
const getNewToken = () => {
	return new Promise((resolve, reject) => {
		let { state } = store
		if (state.token && state.sessionKey && state.userId) {
			uni.login({
				success(ress) {
					uni.request({
						url: baseUrl + '/app/noAuth/wx/login_by_wx', //获取最新token接口地址
						method: 'POST',
						data: { code: ress.code },
						complete: res => {
							let {
								data: { data, head },
							} = res
							if (head.code === 200) {
								uni.setStorageSync('sessionKey', data.sessionKey)
								uni.setStorageSync('token', data.token)
								uni.setStorageSync('userId', data.user.id)
								if (store && store.commit) {
									store.commit('changeUserInfo', data)
								}
								resolve()
							} else {
								reject()
							}
						},
					})
				},
				fail(err) {
					reject()
					console.error('wx login fail', err)
				},
			})
		}
	})
}
